//
//  HMEmoticonPageCell.swift
//  MyWeibo
//
//  Created by apple on 16/4/30.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class HMEmoticonPageCell: UICollectionViewCell {
    
    //供外界设置数组的属性
    var emoticons:[HMEmoticon]?{
        
        //数组属性设置好之后设置button属性
        didSet{
            
            //让表情按钮显示数据
            guard let e = emoticons else {
                return
            }
            //先隐藏所有按钮 然后遍历用一个打开一个
            for value in emoticonButtons {
                
                value.hidden = true
            }
            
            //遍历表情数组设置表情数据
            for (index,emoticon) in e.enumerate() {
                //添加数据
                let button = emoticonButtons[index]
                //显示按钮
                button.hidden = false
                //赋值自定义button
                button.emoticon = emoticon
                
            }
        }
        
    }
    
    
    
    //创建一个数组记录当前数组
    lazy var emoticonButtons:[HMEmoticonButton]=[]
    
    //给messageLabel赋值 测试用
    var indexPath:NSIndexPath?{
        didSet{
         
         messageLabel.hidden = indexPath?.section != 0
        }
    }
    
    
    //初始化init方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        
        //设置item颜色显示
//        backgroundColor = RandomColor
        addChildButtons()
        //添加一个消息label
        contentView.addSubview(messageLabel)
        //添加删除按钮
        contentView.addSubview(deleteButton)
        
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-10)
        }

        
        // 给contentView添加长按的手势
        let longPress = UILongPressGestureRecognizer(target: self, action: "longPress:")
        // 最短的触发时间
        //        longPress.minimumPressDuration = 5
        contentView.addGestureRecognizer(longPress)
    }

    //添加20个表情按钮
    private func addChildButtons(){
        
        //设置最大数组
        let maxCount = HMEmoticonKetboardPageEmticonCount
        
        //循环添加按钮
        for _ in 0..<maxCount {
            
            //添加button
            let button = HMEmoticonButton()
            //添加背景颜色
//            button.backgroundColor = RandomColor
            
            //给每个button添加方法
            button.addTarget(self, action: "emoticonButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            //添加到contentView上
            contentView.addSubview(button)
            
            //添加到数组中
            emoticonButtons.append(button)
            
        }
        
  
    }
    
    // MARK: - 监听事件
 
    @objc private func longPress(ges: UILongPressGestureRecognizer){
        
        
        // 1. 取到手指所在的位置
        let location = ges.locationInView(ges.view)
        
        print(location)
        
        // 2. 找到该位置所对应的按钮
        func buttonWithLocation(location: CGPoint) -> HMEmoticonButton? {
            for value in emoticonButtons {
                //if value的范围是否包含传入的点，如果包含，直接返回value
                if CGRectContainsPoint(value.frame, location) {
                    return value
                }
            }
            return nil
        }
        
        // 通过点找到点对应的表情按钮
        guard let button = buttonWithLocation(location) else {
            popView.removeFromSuperview()
            return
        }
        
        switch ges.state {
        case .Began,.Changed:
            if popView.emoticonButton.emoticon == button.emoticon {
                return
            }
            
            // 0. 取到最上层的window
            let window = UIApplication.sharedApplication().windows.last!
            // 2.1 坐标转换：将按钮在contentView里面的坐标值转换到window上面
            // converRect： __.convertRect(__, toView: __)
            let rect = button.superview!.convertRect(button.frame, toView: window)
            // 中心点一样
            popView.center.x = CGRectGetMidX(rect)
            popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
            // 给 PopView里面的按钮赋值
            popView.emoticonButton.emoticon = button.emoticon
            // 3. 添加
            window.addSubview(popView)
        default:
            popView.removeFromSuperview()
        }
        
    }

    // 表情按钮点击的事件
    @objc private func emoticonButtonClick(button: HMEmoticonButton) {
        print(button.emoticon?.chs)
        
        
        
        //取到最上层的window
        let window = UIApplication.sharedApplication().windows.last!
        
        // 初始化一个popView
        let popView = HMEmoticonPopView.popView()
        //设置当前popView的位置
        // 坐标转换：将按钮在contentView里面的坐标值转换到window上面
        let rect = button.superview!.convertRect(button.frame, toView: window)
        
        // 中心点一样
        popView.center.x = CGRectGetMidX(rect)
        popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
        // 给 PopView里面的按钮赋值
        popView.emoticonButton.emoticon = button.emoticon
        // 3. 添加
        window.addSubview(popView)
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
//        }
        popView.removeFromSuperview()
        
    }
    
    //设置cell的布局
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        //设置每一个按钮的宽度
        let itemW = self.frame.width / CGFloat(HMEmoticonKetboardMaxCol)
        //设置每一个按钮的高度
        let itemH = (self.frame.height - 25) / CGFloat(HMEmoticonKetboardMaxRow)
        
        //调整20个按钮的位置  通过下标来遍历
        for (index,value) in emoticonButtons.enumerate() {
            
            
            //计算所在的行
            let col = index % HMEmoticonKetboardMaxCol
            //计算所在的列
            let row = index / HMEmoticonKetboardMaxCol
            
            //计算出x的位置
            let x = CGFloat(col) * itemW
            //计算出y的位置
            let y = CGFloat(row) * itemH
            
            
            //设置每个item的大小
            value.frame = CGRect(x: x, y: y, width: itemW, height: itemH)
            
        }
        
        //设置删除按钮的布局
        
        let deleteButtonX = self.frame.width - itemW
        let deleteButtonY = self.frame.height - itemH - 25
        
        //设置删除按钮
        deleteButton.frame = CGRect(x: deleteButtonX, y: deleteButtonY, width: itemW, height: itemH)
        
    }
    //添加删除按钮
    private lazy var deleteButton:UIButton = {
        //创建button
        let button = UIButton()
        //设置不同状态的图片
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        
        return button
    }()
    
    
    //添加一个消息label
    private lazy var messageLabel:UILabel = {
        
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 13)
        
        label.text = "最近使用的表情"
        
        return label
    }()
    
    /// 长按出现的popView
    private lazy var popView: HMEmoticonPopView = {
        let popView = HMEmoticonPopView.popView()
        return popView
    }()
    
}
